import React,{Component} from 'react';
import {Route,Link,Redirect} from "react-router"
import {Router} from "react-router-dom"
import WtHostPost from '../util/WtHostPost'
import WtHome from "../WtHome";
import WtLogin from "../auth/WtLogin";
import WtForgotPassword from "../auth/WtForgotPassword";
import {ACTION_AUTH as ACTTON_AUTH} from "../store/action";
import connect from "react-redux/es/connect/connect";
import history from './history'
import WtForgotPasswordActive from "../auth/WtForgotPasswordActive";
class WtLoading extends Component{
    render() {
        return (
            <div>
                loading~
            </div>
        );
    }
}
class WtRoute extends Component{
    loadUserInfo =()=>{
        WtHostPost('/login',{},true).then(({json,header})=>{
            if (json.code===0){
                this.props.login(json.user);
            }else{
                throw json;
            }
        }).catch(e=>{
            this.props.loginFail();
        });
    };
    //判断用户是否登录，如果登录跳转到WtHome界面,{...props}..的意思将props对象参数取出来再赋值给另外一个对象
    authCheck = (props) =>{
        const {auth}=this.props;
        if (auth.login){
            return <WtHome {...props}/>;
        }else if(auth.try===false){
            this.loadUserInfo();
            return <WtLoading/>;
        }else {
            return <Redirect to="/login"/>;
        }
    };

    loginCheck = (props) =>{
        const {auth}=this.props;
        if (auth.login){
            let toLink='/home/book-list';
            return <Redirect to={toLink}/>;
        }else if(auth.try===false){
            this.loadUserInfo();
            return <WtLoading/>
        }else {
            return <WtLogin {...props}/>;
        }
    };

    render(){
        return(
            <Router history={history}>
                <div style={{height:'100%'}}>
                    <Route path="/" render={this.authCheck} exact/>
                    <Route path="/login" render={this.loginCheck}/>
                    <Route path="/forgot-password" Component={WtForgotPassword}/>
                    <Route path="/forgot-password-active" component={WtForgotPasswordActive}/>
                    <Route path="/home/:secondLevel" render={this.authCheck}/>
                </div>
            </Router>
        );
    }
}
const mapStateToProps = (state)=>{
    return{
        auth:state.auth,
    }
}
const mapDisPatchToprops={
    login:(userInfo)=>{
        return {
            type:ACTTON_AUTH.LOGIN,
            payLoad:{userInfo}
        }
    },
    loginFail:()=>{
        return{
            type:ACTTON_AUTH.LOGIN_FAIL,
        }
    },
};

export default connect(mapStateToProps,mapDisPatchToprops)(WtRoute);
